<template>
  <view @longpress="handleShowParam" >
    <view  class="fixed-top" v-show="showParam">
      <u-collapse>
        <u-collapse-item :title="param.title" name="invInfo">
          <view>
            <u-form>
              <u-form-item label="订单号" @click="handleShowOrder">
                <u--input
                  placeholder="请输入订单号"
                  border="surround"
                  :disabled="true"
                  clearable
                  v-model="param.orderNo"
                ></u--input>
              </u-form-item>
              <u-form-item label="物料编码">
                <u--input
                  placeholder="请输入物料编码"
                  border="surround"
                  clearable
                  v-model="param.invCode"
                ></u--input>
              </u-form-item>
            </u-form>
          </view>
        </u-collapse-item>
      </u-collapse>
    </view>
    <u-list  @scrolltolower="scrolltolower" :pagingEnabled="true" :showScrollbar="true" @scrollWithAnimation="true" :key="listKey">
      <u-list-item v-for="(item, index) in items" :key="index" :class="['custom-list-item',`status-${item.detailStatus}`]" >
       <view @click="handleMakeShow(item)">
         <u-row>
           <u-col>
             <u-cell :title="`单据类型：${getDictValue('over_source_type', item.sourceType)}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`仓库：${item.warehouseCode}`"></u-cell>
           </u-col>
         </u-row>
         <u-row v-show="item.orderNo">
           <u-col>
             <u-cell :title="`订单：${formatStr(item.orderNo)}`"></u-cell>
           </u-col>
         </u-row>
         <u-row v-show="item.remake">
           <u-col>
             <u-cell :title="`备注：${formatStr(item.remake)}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`部门：${item.depName}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`物料编码：${item.invCode}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`物料名称：${item.invName}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`单位：${item.unitName}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`数量：${item.qty}`"></u-cell>
           </u-col>
         </u-row>
         <u-row>
           <u-col>
             <u-cell :title="`状态：${getDictValue('over_form_status', item.detailStatus)}`"></u-cell>
           </u-col>
         </u-row>
       </view>
      </u-list-item>
    </u-list>
    <u-loading-icon :show="loading" text="加载中" textSize="18"></u-loading-icon>
    <u-modal :show="show" :title="title" :content='content' showCancelButton :confirmText="confirmText"
             :showConfirmButton="showConfirmButton" @confirm="handleConfirm"  @cancel="show = false">
      <u-form :model="form" ref="uForm">
        <u-form-item label="物料编码">
          <u--input
              placeholder="请输入物料编码"
              border="surround"
              clearable
              :disabled="true"
              v-model="form.invCode"
          ></u--input>
        </u-form-item>
        <u-form-item label="单据数量">
          <u--input
              placeholder="请输入单据数量"
              border="surround"
              clearable
              :disabled="true"
              v-model="form.qty"
          ></u--input>
        </u-form-item>
        <u-form-item label="实发数量">
          <u--input
              placeholder="请输入实发数量"
              border="surround"
              type="number"
              clearable
              v-model="form.verifiedQty"
          ></u--input>
        </u-form-item>
      </u-form>
    </u-modal>
    <u-picker :show="showOrder" @confirm="confirmOrder" :columns="orders" @cancel="showOrder = false"></u-picker>
  </view>
</template>

<script>

import {getDictValue, initDict} from "@/utils/dictUtil";
import {formConfirm, formRefuse, getOrders, getStockFormList} from "@/api/work/stockTrace/bookKeep";
import {formatStr} from "@/api/work/utils";
import {dealBarCde, destroyScan, initScan} from "@/utils/scanUtil";

export default {
  components: {},
  data() {
    return {
      items: [],
      listKey: Date.now(),
      loading:  false,
      initScanFlag:false,
      param: {
        title: '',
        orderNo: null,
        invCode: null,
        pageNum: 0,
        pageSize: 10,
      },
      show: false,
      showParam: false,
      showOrder:false,
      title: '展开显示查询条件',
      content: '',
      confirmText:  '确认',
      showConfirmButton: true,
      refuseFlag: false,
      tempItem: {},
      form: {
        invCode: null,
        verifiedQty: null,
      },
      tempVerifiedQty: null,
      orders: [],
      handlePdaScan: null,
    };
  },
  beforeDestroy() {
    if (this.initScanFlag) {
      destroyScan(this.handlePdaScan);
    }
  },
  created() {
    this.loadMore();
    initDict(['over_source_type', 'over_form_status'])
    let that = this;
    this.handlePdaScan = function (res) {
      let barCode =  dealBarCde(res);
      if (barCode != null && barCode.invCode != null) {
        that.param.orderNo = null;
        that.param.invCode = barCode.invCode;
        that.param.title = '按物料编码处理：' + that.param.invCode;
        that.refreshData();
      }
    };
    this.initScanFlag = initScan(this.handlePdaScan)
  },
  onShow() {
    let orders1 = [];
    this.orders = [orders1];
    getOrders().then(res => {
      if (res.data.length > 0) {
        res.data.forEach(item => orders1.push(item));
      }
    });
  },
  methods: {
    formatStr,
    getDictValue,
    handleShowParam() {
      this.showParam = true;
      setTimeout(() => {
        this.showParam = false;
      }, 5000);
    },
    handleShowOrder() {
      this.showOrder = true;
      this.showParam = false;
    },
    confirmOrder(e) {
      this.showParam = false;
      this.showOrder = false;
      this.param.orderNo = e.value[0];
      this.param.title = '按订单处理：' + this.param.orderNo;
      this.param.invCode = null;
      this.refreshData();
    },
    scrolltolower() {
      if (this.items.length >= this.total) {
        this.$modal.showToast("没有更多数据了");
        return;
      }
      // 计算最大页数
      let maxPage = Math.ceil(this.total / this.param.pageSize);
      if (maxPage === this.param.pageNum) {
        this.$modal.showToast("已到最后一页");
        return;
      }
      this.loadMore()
    },
    loadMore() {
      this.loading = true;
      this.param.pageNum = this.param.pageNum + 1;
      getStockFormList(this.param).then(res => {
        this.listKey = Date.now();
        this.total = res.total;
        if (res.rows.length > 0) {
          res.rows.forEach(item => this.items.push(item));
        } else {
          this.$modal.msg("无数据！");
        }
        this.loading = false;
      });
    },
    handleMakeShow(item) {
      this.content = '对物料' + item.invCode + '记账核实';
      this.title = '确认';
      this.confirmText = '确认';
      this.tempItem = item;
      this.show = true;
      this.showConfirmButton = true;
      this.form.invCode = item.invCode;
      this.form.qty = item.qty;
      this.form.sourceType = item.sourceType;
      this.form.verifiedQty = item.verifiedQty;
      this.tempVerifiedQty = item.verifiedQty;
    },
    refreshData() {
      this.items = [];
      this.param.pageNum = 0;
      this.loadMore();
    },
    handleConfirm() {
      this.showConfirmButton = false;
      if (this.form.verifiedQty === undefined || this.form.verifiedQty === null || this.form.verifiedQty === '') {
        this.$modal.msgError('请输入实发数量！');
        this.showConfirmButton = true;
        return;
      }
      if (this.form.sourceType === 4 && this.form.verifiedQty > 0) {
        this.$modal.msgError('退库数量不可大于0！已修正，请继续提交');
        this.form.verifiedQty = - this.form.verifiedQty;
        this.showConfirmButton = true;
        return;
      }
      if ((this.form.sourceType === 3 || this.form.sourceType === 5)&& this.form.verifiedQty < 0) {
        this.$modal.msgError('仓库出库数量不可小于0！已修正，请继续提交');
        this.form.verifiedQty = - this.form.verifiedQty;
        this.showConfirmButton = true;
        return;
      }
      this.tempItem.verifiedQty = this.form.verifiedQty;
      if (this.refuseFlag) {
        // 否决逻辑
        formRefuse(this.tempItem).then(() => {
              this.refreshData();
              this.show = false;
            }
        ).catch(error => {
          this.$modal.msgError(error);
          this.showConfirmButton = true;
        });
      } else {
        // 确认逻辑
        formConfirm(this.tempItem).then(() => {
          this.refreshData();
          this.show = false;
        }).catch(error => {
          this.$modal.msgError(error);
          this.showConfirmButton = true;
        });
      }
    }
  },
  watch: {
    'form.verifiedQty': function(newVal, oldVal) {
      if (this.tempVerifiedQty === null) {
        return;
      }
      if (parseFloat(this.tempVerifiedQty) !== parseFloat(newVal)) {
        this.refuseFlag = true;
        this.confirmText = '否决';
      } else {
        this.refuseFlag = false;
        this.confirmText = '确认';
      }
    }
  },
};</script>
<style>
.custom-list-item {
  /* 如果需要让整个列表项点击区域都生效，可能还需要下面这行 */
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
  height: 100%; /* 根据实际情况调整高度 */
}

.status-0 {
  background-color: #ADD8E6;
}

.status-1 {
  background-color: #43dee3;
}

.status-3 {
  background-color: #CCCCCC;
}

.fixed-top {
  position: fixed;
  top: 0;          /* 关键修改：从底部改为顶部 */
  left: 0;
  right: 0;
  padding: 10px;
  text-align: center;
  background-color: #fff;
  z-index: 999;
  /* 可选：添加底部边框作为视觉区分 */
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
